package com.sso.server.controller;

import com.sso.server.store.UserTokenStorage;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
public class MyIndexController {

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public ModelAndView toLogin(String redirectURL, ModelAndView modelAndView) {
        modelAndView.setViewName("login");
        modelAndView.addObject("redirectUrl", redirectURL);
        return modelAndView;
    }

    /**
     * 登录
     *
     * @param account
     * @param password
     * @param modelAndView
     * @return
     */
    @RequestMapping("/login")
    public ModelAndView login(String account, String password, String redirectUrl, ModelAndView modelAndView, HttpSession httpSession) {
        if ("admin".equals(account) && "123456".equals(password)) {
            String token = UUID.randomUUID().toString();
            modelAndView.setViewName("redirect:"+redirectUrl);
            httpSession.setAttribute("token", token);
            modelAndView.addObject("token",token);
            UserTokenStorage.getStorage().put(token,"admin");
            return modelAndView;
        }
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping("/loginCheck")
    public ModelAndView loginCheck(String redirectURL, ModelAndView modelAndView, HttpSession httpSession) {
        String token = (String) httpSession.getAttribute("token");
        if(StringUtils.isEmpty(token)){
            modelAndView.addObject("redirectUrl", redirectURL);
            modelAndView.setViewName("login");
            return modelAndView;
        }
        modelAndView.addObject("token",token);
        modelAndView.setViewName("redirect:"+redirectURL);
        return modelAndView;
    }


    @RequestMapping("/verify")
    public String verify(String token) {
        return UserTokenStorage.getStorage().get(token);
    }


}
